package com.ayf.payment.game.api.service;

import com.ayf.payment.game.api.dto.MerchantConfigDTO;
import com.ayf.payment.game.api.utils.SnowFlakeUtils;
import com.swwx.charm.commons.lang.utils.LogPortal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 *
 *
 * @author wwl
 * @date 2020/4/3 13:50
 */
@Component
public class MerchantRepository {

    public static final long MERCHANT_EXPIRED_SECOND = 7 * 24 * 60L * 60 * 2;

    private static final String MERCHANT_CACHE="G_XY_MERCHANT-";

    @Autowired
    private MerchantConfigService merchantConfigService;

    @Autowired
    private RedisTemplate baseRedisTemplate;

    public void set(Integer key, MerchantConfigDTO value){
        baseRedisTemplate.opsForValue().set(MERCHANT_CACHE+key,value,MERCHANT_EXPIRED_SECOND, TimeUnit.SECONDS);
    }
    public MerchantConfigDTO get(Integer key){
        MerchantConfigDTO merchantConfigDTO= null;
        try {
            merchantConfigDTO = (MerchantConfigDTO)baseRedisTemplate.opsForValue().get(MERCHANT_CACHE+key);
        } catch (Exception e) {
            LogPortal.error("{} 从缓存获取商户配置发送{}异常",e,SnowFlakeUtils.getTraceId(),e.getClass().getName());
        }
        if(merchantConfigDTO==null){
            merchantConfigDTO= merchantConfigService.getMerchantConfigDTO(key);
            set(merchantConfigDTO.getMerchantId(),merchantConfigDTO);
        }
        return merchantConfigDTO;
    }

    public Set getKeys(String key){
        return  baseRedisTemplate.keys(key);
    }

    public void del(Integer key){
        baseRedisTemplate.delete(MERCHANT_CACHE+key);
    }
}
